package com.wxl.www.wxl.shiro.controller;

import com.wxl.www.wxl.shiro.entity.UserInfo;
import com.wxl.www.wxl.shiro.service.UserInfoService;
import com.wxl.www.wxl.shiro.utils.AOP.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/sys/welcome")
    public String Welcome(){
        return "sys/welcome.html";
    }

    @GetMapping("/login")
    public String toLoginPage(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Object login(@RequestParam String userName,@RequestParam String passWord){
        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            return "password error!";
        } catch (UnknownAccountException uae) {
            return "username error!";
        }

        UserInfo user = userInfoService.findUserByName(userName);
        subject.getSession().setAttribute("user", user);
        return "SUCCESS";
    }

    @RequestMapping("/index")
    @RequiresUser
    public String index(){
        return "index";
    }

    /**
     * 后台管理系统
     * @return
     */
    @LoginUser
    @RequestMapping("/system/index")
    @RequiresPermissions("sys:user")
    public String systemIndex(){
        return "sys/index";
    }
}
